package com.heritage.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "heritages")
@Data
@NoArgsConstructor
@AllArgsConstructor
// 排除可能导致循环引用的字段
@ToString(exclude = {"comments", "likes", "category"})
public class Heritage {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(length = 1000)
    private String description;

    @Column(length = 5000)
    private String history;

    @Column(length = 2000)
    private String features;

    @Column(length = 2000)
    private String value;

    @Column(length = 2000)
    private String protection;

    private String image;

    private String level;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id")
    private Category category;

    @OneToMany(mappedBy = "heritage", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<Comment> comments = new HashSet<>();

    @OneToMany(mappedBy = "heritage", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<Like> likes = new HashSet<>();

    @CreationTimestamp
    private LocalDateTime createdAt;

    @UpdateTimestamp
    private LocalDateTime updatedAt;

    // 添加辅助方法来管理双向关系
    public void addComment(Comment comment) {
        comments.add(comment);
        comment.setHeritage(this);
    }

    public void removeComment(Comment comment) {
        comments.remove(comment);
        comment.setHeritage(null);
    }

    public void addLike(Like like) {
        likes.add(like);
        like.setHeritage(this);
    }

    public void removeLike(Like like) {
        likes.remove(like);
        like.setHeritage(null);
    }
}
